package com.wjw.demo;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * Created by Administrator on 2017/4/2.
 */

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

    private Context context;
    private List<String> list;
    private LayoutInflater mInflater;

    //接口实例
    private Dianji mDianji;

    //注册接口的方法
    public void setDianji(Dianji mDianji) {
        this.mDianji = mDianji;
    }

    public MyAdapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
        mInflater = LayoutInflater.from(context);
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = mInflater.inflate(R.layout.item_recycler, parent, false);
        MyViewHolder mVH = new MyViewHolder(view);
        return mVH;
    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {
        holder.tv.setText(list.get(position));

        //条目点击事件
        if (mDianji != null) {
            //单击
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //!!!!!!
                    int layoutPosition = holder.getLayoutPosition();
                    mDianji.onItemClick(holder.itemView, layoutPosition);
                }
            });

            //长按
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    //!!!!!!
                    int layoutPosition = holder.getLayoutPosition();
                    mDianji.onItemLongClick(holder.itemView, layoutPosition);
                    return true;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    //添加条目方法
    public void addData(int pos) {
        list.add(pos, "Add one");
        notifyItemInserted(pos);
    }

    //删除条目方法
    public void delData(int pos) {
        list.remove(pos);
        notifyItemRemoved(pos);
    }
}

class MyViewHolder extends RecyclerView.ViewHolder {

    TextView tv;

    public MyViewHolder(View itemView) {
        super(itemView);
        tv = (TextView) itemView.findViewById(R.id.id_tv);
    }
}
